<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class CategoryController extends Controller
{
    /**
     * 显示分类页面
     */
    public function index(): Response
    {
        // 获取所有主分类及其产品
        $categories = \App\Models\Category::with([
            'products' => function ($query) {
                $query->with([
                    'variants' => function ($variantQuery) {
                        $variantQuery->where('is_active', true)->orderBy('sort_order');
                    }
                ])
                ->where('is_active', true)
                ->orderBy('sort_order');
            }
        ])
        ->where('is_active', true)
        ->orderBy('sort_order')
        ->get();

        return Inertia::render('Shop/Categories', [
            'categories' => $categories
        ]);
    }

    /**
     * 显示单个分类详情页
     */
    public function show(Request $request, string $slug): Response
    {
        // 根据 slug 查找分类
        $category = \App\Models\Category::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();

        // 构建查询
        $query = \App\Models\Product::with([
            'images',
            'variants' => function ($query) {
                $query->where('is_active', true)->orderBy('sort_order');
            }
        ])
        ->whereHas('categories', function ($query) use ($category) {
            $query->where('categories.id', $category->id);
        })
        ->where('is_active', true);

        // 价格筛选
        if ($request->has('price_range') && $request->price_range !== 'all') {
            $range = $request->price_range;
            if (str_contains($range, '-')) {
                [$min, $max] = explode('-', $range);
                $query->whereBetween('price', [(float)$min, (float)$max]);
            } else {
                // 例如 "10000+" 的情况
                $min = (float)str_replace('+', '', $range);
                $query->where('price', '>=', $min);
            }
        }

        // 排序
        $sortBy = $request->get('sort_by', 'default');
        switch ($sortBy) {
            case 'price-asc':
                $query->orderBy('price', 'asc');
                break;
            case 'price-desc':
                $query->orderBy('price', 'desc');
                break;
            case 'newest':
                $query->orderBy('created_at', 'desc');
                break;
            default:
                $query->orderBy('sort_order')->orderBy('created_at', 'desc');
        }

        $products = $query->get()->map(function ($product) {
            return [
                'id' => $product->id,
                'name' => $product->name,
                'slug' => $product->slug,
                'description' => $product->description,
                'price' => $product->price,
                'compare_price' => $product->compare_price,
                'discount_percentage' => $product->compare_price && $product->compare_price > $product->price
                    ? round((($product->compare_price - $product->price) / $product->compare_price) * 100)
                    : null,
                'image' => $product->images->where('is_primary', true)->first()?->image_path ?? $product->images->first()?->image_path ?? '/images/iphone.jpg',
                'is_featured' => $product->is_featured,
                'product_type' => $product->product_type,
            ];
        });

        return Inertia::render('Shop/CategoryDetail', [
            'category' => [
                'id' => $category->id,
                'name' => $category->name,
                'slug' => $category->slug,
                'description' => $category->description,
            ],
            'products' => $products,
            'filters' => [
                'price_range' => $request->get('price_range', 'all'),
                'sort_by' => $request->get('sort_by', 'default'),
            ]
        ]);
    }
}
